<?php


namespace app\admin\controller;


use app\common\model\ProtocolModel;
use think\facade\Request;
use think\Validate;

class ProtocalController extends BaseController
{
    public function index()
    {
        return $this->fetch();
    }

    public function edit()
    {
        $protocal = ProtocolModel::where(['id' => Request::param('id')])->find();
        $this->assign('protocal', $protocal);
        return $this->fetch();
    }

    public function getlist()
    {
        $list = ProtocolModel::field('content', true)->select();
        return self::bulidSuccess($list);
    }

    public function add()
    {
        if (Request::isPost()) {
            $all_param = Request::param();

            $validate = new Validate([
                'title'      => 'require',
                'content'    => 'require',
            ], [
                "title"      => "请输入标题",
                'content'    => '请填充内容',
            ]);

            if (!$validate->check($all_param)) {
                return self::bulidFail($validate->getError());
            }
            $protocal   = new ProtocolModel($all_param);
            $protocal->content = Request::param('content');
            $protocal->title   = Request::param('title');
            $protocal->desc    = Request::param('desc');

            if ($protocal->save()) {
                // 记录日志
                $log_content = "编辑协议规范，ID：标题：{$protocal->title}";
                parent::addAdminLog($log_content);
                return self::bulidSuccess();
            }
        }
        return $this->fetch();
    }

    public function edit_post()
    {
        $protocal          = ProtocolModel::where(['id' => Request::param('id')])->find();
        if (!$protocal) {
            $protocal = new ProtocolModel();
        }
        $protocal->content = Request::param('content');
        $protocal->title   = Request::param('title');
        $protocal->desc    = Request::param('desc');
        if ($protocal->save()) {
            // 记录日志
            $log_content = "编辑协议规范，ID：{$protocal->id}，标题：{$protocal->title}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    public function del_post()
    {
        $id          = Request::param('id');
        $order_model = ProtocolModel::get($id);
        if (!$order_model) {
            return self::bulidFail('协议不存在');
        }
        if (ProtocolModel::destroy($id)) {
            // 记录日志
            $log_content = "删除协议，ID：{$id}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }

        return self::bulidFail();
    }
}
